package ua.kiev.tosik.price.modules.search.gui;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.gui.MainWindow;
import ua.kiev.tosik.price.models.Prices;
import ua.kiev.tosik.price.modules.search.conf.ModuleConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class PricesDialog {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.search.gui");
	private MainPanel mainPanel;
	private JDialog dialog;
	private ActionListener closeAction;
	private ActionListener copyAction;
	private Prices prices;
	private ModuleConfig config;

	private JTextField companyField;
	private JTextField articleInternalField;
	private JTextField articleField;
	private JTextArea nameField;
	private JLabel dateField;
	private JTextField priceField;
	private JLabel existenceField;

	private JButton copyButton;
	private JButton closeButton;
	private JButton addToNotepadButton;

	private DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

	public PricesDialog(MainPanel mainPanel) {
		logger.debug("First Initialize PricesDialog");
		this.mainPanel = mainPanel;
		closeAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				close();
			}
		};
		copyAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if ( PricesDialog.this.prices != null ) {
					copyToBuffer(PricesDialog.this.prices);
				}
			}
		};
		config = ModuleConfig.getInstance();

		dialog = new JDialog(MainWindow.getInstance().getFrame());
		dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		dialog.getRootPane().registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
		dialog.setTitle(config.get("search.prices.editor.title"));
		dialog.setIconImage( new ImageIcon(config.get("search.prices.editor.icon")).getImage() );
		dialog.setModal(true);
		dialog.setResizable(false);
		dialog.setSize( new Dimension(460, 440) );
		dialog.setLayout( new BorderLayout() );
		dialog.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent ev) {
				close();
			}
		});

		initFields();
		closeButton = new JButton(config.get("search.prices.editor.button.close.text"), new ImageIcon(config.get("search.prices.editor.button.close.icon")));
		closeButton.addActionListener(closeAction);
		copyButton = new JButton(config.get("search.prices.editor.button.copy.text"), new ImageIcon(config.get("search.prices.editor.button.copy.icon")));
		copyButton.addActionListener(copyAction);
		addToNotepadButton = new JButton(config.get("search.prices.editor.button.addToNotepad.text"), new ImageIcon(config.get("search.prices.editor.button.addToNotepad.icon")));
		// addToNotepadButton.addActionListener();

		dialog.add("Center", buildForm());
		dialog.getRootPane().setDefaultButton(closeButton);
	}

	public void setPrices(Prices prices) {
		this.prices = prices;
		if ( prices == null ) {
			return;
		}
		fillFields(prices);
	}

	public void open() {
		if ( prices == null ) {
			logger.warn("Can't open PricesDialog without prices data");
			return;
		}
		dialog.pack();
		dialog.setLocationRelativeTo(mainPanel.getPanel());
		dialog.setVisible(true);
	}

	public void close() {
		setPrices(null);
		fillFields(new Prices());
		dialog.setVisible(false);
		dialog.dispose();
	}

	private void copyToBuffer(Prices prices) {
		List<String> fieldsList = new ArrayList<String>();
		StringBuilder sb = new StringBuilder();
		String delim = "\t";

		fieldsList.add(String.valueOf(prices.getId()));
		fieldsList.add(prices.getClientsName());
		fieldsList.add(prices.getArticleInternal());
		fieldsList.add(prices.getArticle());
		fieldsList.add(prices.getName());
		fieldsList.add(String.valueOf(prices.getPrice()).replaceAll("\\.", ","));
		fieldsList.add(prices.getPricesDate().toString());
		fieldsList.add(prices.getExistence());

		sb.append(StringUtils.join(fieldsList, delim)); //.append("\n");
		Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable transferableText = new StringSelection(sb.toString());
		systemClipboard.setContents(transferableText, null);
	}

	private void fillFields(Prices prices) {
		companyField.setText(prices.getClientsName());
		articleInternalField.setText(prices.getArticleInternal());
		articleField.setText(prices.getArticle());
		nameField.setText((prices.getName() != null && prices.getName().length() > 0 )?prices.getName():null);
		priceField.setText(String.valueOf(prices.getPrice()));
		existenceField.setText(prices.getExistence());
		dateField.setText((( prices.getPricesDate() != null ))?dateFormat.format(prices.getPricesDate()):null);
	}

	private void initFields() {
		companyField = new JTextField(30);
		articleInternalField = new JTextField(20);
		articleField = new JTextField(20);
		nameField = new JTextArea();
		nameField.setLineWrap(true);
		// nameField.setEnabled(false);
		// nameField.setBorder( BorderFactory.createEtchedBorder() );
		dateField = new JLabel();
		priceField = new JTextField(10);
		priceField.setHorizontalAlignment(SwingConstants.RIGHT);
		existenceField = new JLabel();
	}

	private JPanel buildForm() {
		FormLayout layout = new FormLayout(
			"right:100px, 10px, left:300px, 10px",
			// "right:pref, 10px, left:pref, 10px",
			"pref, 10px, pref, 10px, pref, 10px, pref, 10px, pref, 10px, pref, 10px, pref, 10px, pref, 10px,"+
			"pref, 10px, center:pref, 10px"
		);

		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		CellConstraints cc = new CellConstraints();

		JLabel label = new JLabel( new ImageIcon(config.get("search.prices.editor.icon.title")) );
		// int fontSize = label.getFont().getSize();
		label.setFont(new Font(label.getFont().getFontName(), Font.BOLD, 18));
		label.setText(config.get("search.prices.editor.title"));
		label.setHorizontalAlignment(SwingConstants.LEFT);
		builder.add(label, cc.xyw(1, 1, 3));
		builder.addSeparator("", cc.xyw(1, 3, 4));

		Font f = companyField.getFont().deriveFont(Font.BOLD);

		builder.addLabel(config.get("search.price.table.filed.clientsName"), cc.xy(1, 5)).setFont(f);
		builder.add(companyField, cc.xy(3, 5));

		builder.addLabel(config.get("search.price.table.field.articleInternal"), cc.xy(1, 7)).setFont(f);
		builder.add(articleInternalField, cc.xy(3, 7));

		builder.addLabel(config.get("search.price.table.field.article"), cc.xy(1, 9)).setFont(f);
		builder.add(articleField, cc.xy(3, 9));

		builder.addLabel(config.get("search.price.table.field.name"), cc.xy(1, 11)).setFont(f);
		JScrollPane scrollPane = new JScrollPane(nameField, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setPreferredSize( new Dimension(300, 100) );
		builder.add(scrollPane, cc.xyw(3, 11, 2));

		builder.addLabel(config.get("search.price.table.field.date"), cc.xy(1, 13)).setFont(f);
		builder.add(dateField, cc.xy(3, 13));

		builder.addLabel(config.get("search.price.table.field.price"), cc.xy(1, 15)).setFont(f);
		builder.add(priceField, cc.xy(3, 15));

		builder.addSeparator("", cc.xyw(1, 17, 4));
		
		builder.add(createButtonBar(), cc.xyw(1, 19, 4));

		return builder.getPanel();
	}

	private JPanel createButtonBar() {
		JPanel panel = new JPanel();
		panel.add(copyButton);
		panel.add(addToNotepadButton);
		panel.add(closeButton);
		addToNotepadButton.setEnabled(false);
		return panel;
	}

}
